from fastapi import APIRouter, Depends, HTTPException
from sqlalchemy.orm import Session
from database.get_db import get_db_pro as get_db
from database.user_db import dataBaseModel, crud as user_crud

router = APIRouter(
    prefix="/user",
    tags=["user"],
    responses={404: {"description": "Not found"}},
)


@router.post("/create_user", response_model=dataBaseModel.User)
async def create_user(user_create: dataBaseModel.UserCreate, db: Session = Depends(get_db)):
    """
    创建用户
    :param user_create: 创建用户的baseModel  请求体
    :param db: 数据库会话
    :return: 新用户信息
    """
    # 检查是否已存在相同用户名的用户
    db_user = user_crud.get_user_by_username(db, user_create.username)
    if db_user:
        raise HTTPException(status_code=400, detail={
            "info": "账号已存在"
        })
    # 获取用户指定的角色信息
    role = user_crud.get_role_by_name(db, user_create.role_name)
    if not role:
        raise HTTPException(status_code=400, detail={
            "info": "角色不存在"
        })
    # 创建新用户
    new_user = user_crud.create_user(db, user_create, role.id)
    # 返回新用户信息
    return new_user


@router.get("/user_info/{username}", response_model=dataBaseModel.User)
async def get_user(username: str, db: Session = Depends(get_db)):
    """
    获取用户信息
    :param username: 用户名
    :param db: 数据库会话
    :return: 用户信息
    """
    # 查找用户
    user_db = user_crud.get_user_by_username(db, username)
    return user_db


@router.post("/create_role", response_model=dataBaseModel.Role)
async def create_role(role: dataBaseModel.RoleCreate, db: Session = Depends(get_db)):
    """
    创建角色
    :param role: 角色信息
    :param db: 数据库会话
    :return:
    """
    # 检查是否已存在相同角色名称的角色
    if user_crud.get_role_by_name(db, role.name):
        raise HTTPException(status_code=400, detail={
            "info": "角色已存在"
        })
    # 创建新角色
    new_role = user_crud.create_roles(db, role)
    # 返回新角色信息
    return new_role
